package com.ewzj.bigdata.app.utils

import com.jess.arms.mvp.IView
import com.trello.rxlifecycle2.LifecycleTransformer
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import com.trello.rxlifecycle2.components.support.RxFragment

import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.annotations.NonNull
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

/**
 * Created by jess on 11/10/2016 16:39
 * Contact with jess.yan.effort@gmail.com
 */

object RxUtils {

    fun <T> applySchedulers(view: IView): ObservableTransformer<T, T> {
        return ObservableTransformer { observable ->
            observable.subscribeOn(Schedulers.io())
                    .doOnSubscribe {
                        view.showLoading()//显示进度条
                    }
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doAfterTerminate {
                        view.hideLoading()//隐藏进度条
                    }.compose(RxUtils.bindToLifecycle<T>(view))
        }
    }

    fun <T> bindToLifecycle(view: IView): LifecycleTransformer<T> {
        if (view is RxAppCompatActivity) {
            return view.bindToLifecycle<T>()
        } else if (view is RxFragment) {
            return view.bindToLifecycle<T>()
        } else {
            throw IllegalArgumentException("view isn't activity or fragment")
        }

    }

}
